//
//  SCSliderView.m
//  OCRDemo
//
//  Created by 党帅 on 2019/6/14.
//  Copyright © 2019 党帅. All rights reserved.
//

#import "SCSliderView.h"

@interface SCSliderView ()

@property (nonatomic, strong) UIView *shapeLayerView;

@property (nonatomic, strong) CAShapeLayer *shapeLayer;

@property (nonatomic, strong) CALayer *leftThumb;
@property (nonatomic, strong) CALayer *rightThumb;

@property (nonatomic, assign) CGFloat thumbCenterY;
@property (nonatomic, assign) CGFloat thumbCenterXLeft;
@property (nonatomic, assign) CGFloat thumbCenterXRight;

@property (nonatomic, assign) CGFloat tolerate;

@property (nonatomic, assign) int moveIndex;

@property (nonatomic, assign) float sliderWidth;
@end

static CGFloat const kLeftMargin = 6.f;

@implementation SCSliderView

- (void)awakeFromNib {
    [super awakeFromNib];
    [self propertyDefault];
    _shapeLayer = [CAShapeLayer layer];
    _shapeLayer.frame = CGRectMake(_thumbCenterXLeft, _thumbCenterY, CGRectGetWidth(self.frame), 3);
    _shapeLayer.backgroundColor = _normalColor.CGColor;
    [self.layer addSublayer:_shapeLayer];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self propertyDefault];
        
        CALayer *layer = [CALayer layer];
        layer.backgroundColor = _normalColor.CGColor;
        layer.frame = CGRectMake(10, _thumbCenterY, kSCScreenWidth - 20, 3);
        [self.layer addSublayer:layer];
        
        _sliderWidth = CGRectGetWidth(frame) - 2 * kLeftMargin - _thumbSize.width;
        
        
        _shapeLayerView = [[UIView alloc] initWithFrame:CGRectMake(_thumbSize.width/2.f + kLeftMargin, 0, _sliderWidth, _thumbSize.height)];
//        _shapeLayerView.backgroundColor = [UIColor grayColor];
        [self addSubview:_shapeLayerView];
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(0, _trackPathHeight/2)];
        [path addLineToPoint:CGPointMake(_sliderWidth, _trackPathHeight/2)];
        
        _shapeLayer = [CAShapeLayer layer];
        _shapeLayer.frame = CGRectMake(0, _thumbCenterY, _sliderWidth, _trackPathHeight);
//        _shapeLayer.backgroundColor = _normalColor.CGColor;
        _shapeLayer.strokeColor = _highlightedColor.CGColor;
        _shapeLayer.lineWidth = _trackPathHeight;
        _shapeLayer.path = path.CGPath;
        _shapeLayer.strokeStart = 0;
        _shapeLayer.strokeEnd = 0;
        [_shapeLayerView.layer addSublayer:_shapeLayer];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    if (_rulerLines.count) {
        NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:SC_TextBlack_Secondary};
        
        float cnt = _rulerLines.count - 1;
        CGFloat space = (_sliderWidth) / cnt;
        for (int i = 0; i < _rulerLines.count; i++) {
            CGFloat x = space * i + 12;
            NSString *string = _rulerLines[i];
            CGFloat w = [string boundingRectWithSize:CGSizeMake(100, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size.width;
            if (i > 0 && i < cnt) {
                x = x + kLeftMargin - w/2;
            } else if (i == cnt) {
                x = x + kLeftMargin - w;
            }
            [string drawAtPoint:CGPointMake(x, 35) withAttributes:attri];
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if ([_delegate respondsToSelector:@selector(sliderMoveBegin)]) {
        [_delegate sliderMoveBegin];
    }
    _sliderWidth = CGRectGetWidth(_shapeLayer.frame);
    
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:_shapeLayerView];
    
    CGRect leftRect = CGRectMake(_thumbCenterXLeft - _tolerate, 0, _thumbSize.width /2.f + _tolerate, _thumbSize.height);
    CGRect rightRect = CGRectMake(_thumbCenterXRight - _thumbSize.width /2.f, _thumbCenterY - _tolerate, _thumbSize.width + _tolerate, _thumbSize.height + _tolerate);
    if (CGRectContainsPoint(leftRect, location)) {
        _moveIndex = 1;
    } else if (CGRectContainsPoint(rightRect, location)) {
        _moveIndex = 2;
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:_shapeLayerView];
    float x = location.x;
    float p = x / _sliderWidth;
    
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    
    if (_moveIndex == 1) {
        if (p >= 0 && x < _thumbCenterXRight - _thumbSize.width / 2) {
            self.lowerValue = p;
            [_delegate sliderViewLowerValueChanged:p upperValue:_upperValue];
        }
    } else if (_moveIndex == 2) {
        if (p <= 1 && x > _thumbCenterXLeft + _thumbSize.width / 2) {
            self.upperValue = p;
            [_delegate sliderViewUpperValueChanged:p lowerValue:_lowerValue];
        }
    }
    [CATransaction commit];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if ([_delegate respondsToSelector:@selector(sliderMoveEnd)]) {
        [_delegate sliderMoveEnd];
    }
    _moveIndex = 0;
}

- (void)setRulerLines:(NSArray *)rulerLines {
    _rulerLines = rulerLines;
    [self setNeedsDisplay];
}

- (void)setThumbImage:(UIImage *)thumbImage {
    _thumbImage = thumbImage;
    self.leftThumb.position = CGPointMake(_thumbCenterXLeft, _thumbCenterY);
    self.rightThumb.position = CGPointMake(_thumbCenterXRight, _thumbCenterY);
}

- (void)setThumbSize:(CGSize)thumbSize {
    _thumbSize = thumbSize;
    _thumbCenterY = thumbSize.height / 2.f;
}

- (void)setNormalColor:(UIColor *)normalColor {
    _normalColor = normalColor;
    _shapeLayer.backgroundColor = normalColor.CGColor;
}

- (void)setHighlightedColor:(UIColor *)highlightedColor {
    _highlightedColor = highlightedColor;
    _shapeLayer.strokeColor = highlightedColor.CGColor;
}

- (void)setLowerValue:(float)lowerValue {
    _lowerValue = lowerValue;
    self.thumbCenterXLeft = _lowerValue * _sliderWidth;
}

- (void)setUpperValue:(float)upperValue {
    _upperValue = upperValue;
    self.thumbCenterXRight = _upperValue * _sliderWidth;
}

-  (void)setThumbCenterXLeft:(CGFloat)thumbCenterXLeft {
    _thumbCenterXLeft = thumbCenterXLeft;
    _shapeLayer.strokeStart = _lowerValue;
    self.leftThumb.position = CGPointMake(_thumbCenterXLeft, _thumbCenterY);
}

- (void)setThumbCenterXRight:(CGFloat)thumbCenterXRight {
    _thumbCenterXRight = thumbCenterXRight;
    _shapeLayer.strokeEnd = _upperValue;
    self.rightThumb.position = CGPointMake(_thumbCenterXRight, _thumbCenterY);
}

- (void)propertyDefault {
    _normalColor = SC_RGB(228, 228, 228);
    _highlightedColor = SC_RGB(255, 218, 27);
    _thumbSize = CGSizeMake(24, 24);
    _thumbCenterY = 12;
    _thumbCenterXLeft = 12;
    _thumbCenterXRight = 36;
    _tolerate = 20;
    _trackPathHeight = 3;
}

- (CALayer *)rightThumb {
    
    if (!_rightThumb) {
        _rightThumb = [CALayer layer];
        _rightThumb.contentsScale = [UIScreen mainScreen].scale;
        _rightThumb.contents = (__bridge id _Nullable)(self.thumbImage.CGImage);
        _rightThumb.bounds = CGRectMake(0, 0, _thumbSize.width, _thumbSize.height);
        [_shapeLayerView.layer addSublayer:_rightThumb];
    }
    return _rightThumb;
}

- (CALayer *)leftThumb {
    
    if (!_leftThumb) {
        _leftThumb = [CALayer layer];
        _leftThumb.contentsScale = [UIScreen mainScreen].scale;
        _leftThumb.contents = (__bridge id _Nullable)(self.thumbImage.CGImage);
        _leftThumb.bounds = CGRectMake(0, 0, _thumbSize.width, _thumbSize.height);
        [_shapeLayerView.layer addSublayer:_leftThumb];
    }
    return _leftThumb;
}

@end
